﻿using System;
using System.Collections.Generic;
using System.Xml.Linq;

using Game;

namespace ApiToolkit
{
	public class StringPropertyEditor_Category : CanvasWidget
	{
		#region MemberWidgets
		BevelledButtonWidget CategoryButton;
		LabelWidget CategoryLabel;
		BevelledButtonWidget ApplyButton;
		#endregion
		
		ContainerWidget Parent;
		StringPropertyEditor.PropertyEditor_String editor;
		string value;
		
		public StringPropertyEditor_Category(int content, string targetProperty, ContainerWidget parent) : base()
		{
			editor = new StringPropertyEditor.PropertyEditor_String(content, targetProperty);
			if(editor.TargetPropertyValue == null) editor.TargetPropertyValue = string.Empty;
			
			Parent = parent;
			var dialogNode = ContentManager.Get<XElement>("Widgets/StringPropertyEditor_Category");
			LoadContents(this, dialogNode);
			
			//初始化字段
			CategoryButton = Children.Find<BevelledButtonWidget>("CategoryButton");
			CategoryLabel = Children.Find<LabelWidget>("CategoryLabel");
			ApplyButton = Children.Find<BevelledButtonWidget>("ApplyButton");
			
			value = editor.TargetPropertyValue.ToString();
			CategoryLabel.Text = value;
		}
		public void CategoryButtonClicked()
		{
			var list = new List<string>(BlocksManager.Categories);

			list.Add("+添加分类");

			Func<object, Widget> fact = (item) =>
			{
				return new LabelWidget()
				{
					Text = item == (object)list[^1] ? item.ToString() : $"{LanguageControl.Get("BlocksManager", item.ToString())}({item.ToString()})",
					HorizontalAlignment = WidgetAlignment.Center
				};
			};
			
			Action<object> onClose = (selectedItem) =>
			{
				if (selectedItem == (object)list[^1])
				{
					var dialog = new TextBoxDialog("填写分类名", string.Empty, 20, (result) =>
					{
						if (BlocksManager.Categories.Contains(result))
						{
							var message = new MessageDialog("无法添加分类", "分类已存在", LanguageControl.Ok, null, null);
							DialogsManager.ShowDialog(Parent, message);
							return;
						}
						//判断是否可添加分类
						
						
						BlocksManager.m_categories.Add(result);
						//添加分类
						
						CategoryButtonClicked();
						//刷新选择分类对话框
					});
					
					DialogsManager.ShowDialog(Parent, dialog);
					return;
				}
				CategoryLabel.Text = selectedItem.ToString();
				value = selectedItem.ToString();
			};


			var selection = new ListSelectionDialog("选择分类", list, 38, fact, onClose);
			
			DialogsManager.ShowDialog(Parent, selection);

		}
		public override void Update()
		{
			if (CategoryButton.IsClicked)
			{
				CategoryButtonClicked();
			}
			if(ApplyButton.IsClicked)
			{
				Apply();
			}
		}
		void Apply()
		{
			editor.Apply(value);
		}
	}
}